﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acme.TestSite.Objects;
using Acme.Northwind.EFDAL;
using Acme.Northwind.EFDAL.Entity;

namespace Acme.TestSite
{
	public partial class TerritoryItem : BasePersistablePage
	{
		#region Page Events

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			cmdSave.Click += new EventHandler(SaveData);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
		}

		#endregion

		#region Methods

		protected override nHydrate.EFCore.DataAccess.NHEntityObject CreateObject(NorthwindEntities context)
		{
			var newItem = new Acme.Northwind.EFDAL.Entity.Territory();
			context.AddItem(newItem);
			return newItem;
		}

		protected override void SetupBindings(NorthwindEntities context)
		{
			var territoryId = this.Request["id"];
			var territory = context.Territory.FirstOrDefault(x => x.TerritoryId == territoryId);
			if (territory == null)
				territory = CreateObject(context) as Acme.Northwind.EFDAL.Entity.Territory;

			Mapper.InitializeList(cboRegion, context.Region.ToList(), Acme.Northwind.EFDAL.Entity.Region.FieldNameConstants.Name, Acme.Northwind.EFDAL.Entity.Region.FieldNameConstants.RegionId);

			Mapper.Map(lblTerritoryId, territory, Acme.Northwind.EFDAL.Entity.Territory.FieldNameConstants.TerritoryId);
			Mapper.Map(txtDescription, territory, Acme.Northwind.EFDAL.Entity.Territory.FieldNameConstants.Name, lblDescription);
			Mapper.Map(cboRegion, territory, Acme.Northwind.EFDAL.Entity.Territory.FieldNameConstants.RegionId, lblRegion);
		}

		#endregion

		#region Event Handlers

		private void cmdCancel_Click(object sender, EventArgs e)
		{
			this.Response.Redirect(SessionHelper.LastTerritoryListSearch);
		}

		protected override void OnDataSavedSucess(EventArgs e)
		{
			base.OnDataSavedSucess(e);
			this.Response.Redirect(SessionHelper.LastTerritoryListSearch);
		}

		#endregion

	}
}